package cn.lytcom.architecture.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import javax.inject.Inject;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.OnClick;
import cn.lytcom.architecture.MyApplication;
import cn.lytcom.architecture.R;
import cn.lytcom.architecture.api.AppRestQueue;
import cn.lytcom.architecture.data.IDataProvider;
import cn.lytcom.architecture.event.InfoEvent;
import cn.lytcom.architecture.manager.DbManager;
import cn.lytcom.architecture.manager.SpManager;
import cn.lytcom.architecture.manager.ThreadManager;
import cn.lytcom.architecture.model.User;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import timber.log.Timber;

public class MainActivity extends BaseActivity {

    @Inject
    IDataProvider dataProvider;
    @Inject
    SpManager spManager;
    @Inject
    DbManager dbManager;
    @Inject
    AppRestQueue appRestQueue;
    @Inject
    ThreadManager threadManager;

    @BindView(R.id.name)
    TextView nameView;
    @BindView(R.id.image)
    ImageView imageView;

    @BindString(R.string.hello_guy)
    String name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.getAppComponent().inject(this);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            }
        });
        EventBus.getDefault().register(this);
        threadManager.post(new Runnable() {
            @Override
            public void run() {
                Timber.i(spManager.getUserName() + " got in threadName: " + Thread.currentThread().getName());
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @OnClick(R.id.get_user_btn)
    void getUser() {
        final ProgressDialog progressDialog = ProgressDialog.show(this, "", getString(R.string.loading));
        appRestQueue.getUser("lytcom").enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                User user = response.body();
                Timber.i("success: " + user.getLogin());
                spManager.setUserName(user.getLogin());
                dbManager.setUser(user);
                progressDialog.dismiss();
                Snackbar.make(nameView, "Get user success!", Snackbar.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                Timber.e(t);
                progressDialog.dismiss();
                Snackbar.make(nameView, "Get user Fail!", Snackbar.LENGTH_LONG).show();
            }
        });
    }

    @OnClick(R.id.get_user_data_btn)
    void getUserData() {
        final ProgressDialog progressDialog = ProgressDialog.show(this, "", getString(R.string.loading));
        dataProvider.getUserByName("lytcom")
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(new Observer<User>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull User user) {
                    Timber.i("success: " + user.getLogin());
                    progressDialog.dismiss();
                    Snackbar.make(nameView, "Get user success!", Snackbar.LENGTH_LONG).show();
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    progressDialog.dismiss();
                    Snackbar.make(nameView, "Get user Fail!", Snackbar.LENGTH_LONG).show();
                }

                @Override
                public void onComplete() {

                }
            });

    }

    @OnClick(R.id.show_user_btn)
    void showUser() {
        User user = dbManager.getUser("lytcom");
        if (user != null) {
            Glide.with(MainActivity.this).load(user.getAvatarUrl()).into(imageView);
            nameView.setText(String.format(name, user.getLogin()));
        }
    }

    @OnClick(R.id.go_info)
    void goInfo() {
        startActivity(new Intent(this, InfoActivity.class));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_main;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    @SuppressWarnings("unused")
    public void onInfoEvent(InfoEvent infoEvent) {
        spManager.setEmailUrl(infoEvent.url);
        Timber.i(spManager.getEmailUrl());
    }
}
